import React, { useState, useEffect } from 'react'
import { View, Input } from '@tarojs/components'
import cls from 'classnames'
import { isDef, } from '@/utils/utils'

import './index.scss'
import { Icon } from '../Icon'
// import classnames from '@/utils/classnames'


function add(num1: number, num2: number) {
    const cardinal = 10 ** 10;
    return Math.round((num1 + num2) * cardinal) / cardinal;
}

function equal(value1: number | string, value2: number | string) {
    return String(value1) === String(value2);
}
export interface IStepperProps {
    value: number
    integer?: boolean
    disabled?: boolean
    inputWidth?: number
    buttonSize?: number
    asyncChange?: boolean
    disableInput?: boolean
    decimalLength?: number
    min?: number
    max?: number
    step?: number
    showPlus?: boolean
    showMinus?: boolean
    disablePlus?: boolean
    disableMinus?: boolean
    longPress?: boolean
    onChange?: (type: string, value: number, evt) => void
}


const LONG_PRESS_START_TIME = 600;
const LONG_PRESS_INTERVAL = 200;

export const Stepper: React.FC<IStepperProps> = (
    {
        disabled = false,
        integer = true,
        showMinus = true,
        showPlus = true,
        decimalLength = 2,
        step = 1,
        min = 0,
        max = Number.MAX_SAFE_INTEGER,
        ...rest
    }
) => {

    const filter = (value) => {
        value = String(value).replace(/[^0-9.-]/g, '');
        if (integer && value.indexOf('.') !== -1) {
            value = value.split('.')[0];
        }
        return value;
    }

    const format = (value) => {
        value = filter(value);

        // format range
        value = value === '' ? 0 : +value;
        value = Math.max(Math.min(max, value), min);

        // format decimal
        if (!integer && isDef(decimalLength)) {
            value = value.toFixed(decimalLength);
        }

        return value;
    }
    const [currentValue, setCurrentValue] = useState<string>(format(rest.value))



    const check = () => {
        const val = format(currentValue);
        if (!equal(val, currentValue)) {
            // th({ currentValue: val });
            setCurrentValue(val)
        }
    }


    useEffect(() => {
        check()
    }, [integer, decimalLength, min, max])

    useEffect(() => {
        if (!equal(currentValue, rest.value)) {
            setCurrentValue(format(rest.value))
        }
    }, [rest.value])


    const isDisabled = (type: string) => {
        if (type === 'plus') {
            return (
                disabled ||
                rest.disablePlus ||
                +currentValue >= max
            );
        }

        return (
            disabled ||
            rest.disableMinus ||
            +currentValue <= min
        );
    }
    const onInput = (event) => {
        const { value = '' } = event.detail || {};

        // allow input to be empty
        if (value === '') {
            return;
        }

        let formatted = filter(value);

        // limit max decimal length
        if (isDef(decimalLength) && formatted.indexOf('.') !== -1) {
            const pair = formatted.split('.');
            formatted = `${pair[0]}.${pair[1].slice(0, decimalLength)}`;
        }

        emitChange(formatted, +formatted < +currentValue ? 'minus' : 'plus', event);
    }

    const emitChange = (value: string, type: string, evt) => {
        if (!rest.asyncChange) {
            //   this.setData({ currentValue: value });
            setCurrentValue(value)
        }

        if (rest.onChange) {
            rest.onChange(type, +value, evt)
        }
        // this.$emit('change', value);
    }

    const onChange = (type: string, evt) => {
        // const { type } = this;
        if (isDisabled(type)) {
            //   this.$emit('overlimit', type);
            return;
        }

        const diff = type === 'minus' ? -step : +step;

        const value = format(add(+currentValue, diff));

        emitChange(value, type, evt);
        // this.$emit(type);
    }

    let longPressTimer
    const longPressStep = (type, evt) => {
        longPressTimer = setTimeout(() => {
            onChange(type, evt);
            longPressStep(type, evt);
        }, LONG_PRESS_INTERVAL);
    }

    const tapHandle = (type: string, evt) => {
        // const { type } = event.currentTarget.dataset;
        // this.type = type;
        
        onChange(type, evt);
    }

    let isLongPress
    const touchStartHandle = (type, evt) => {
        if (!rest.longPress) {
            return;
        }
        clearTimeout(longPressTimer);

        // const { type } = event.currentTarget.dataset;
        // this.type = type;
        isLongPress = false;

        longPressTimer = setTimeout(() => {
            isLongPress = true;
            onChange(type, evt);
            longPressStep(type, evt);
        }, LONG_PRESS_START_TIME);
    }

    const touchEndHandle = () => {
        if (!rest.longPress) {
            return;
        }
        clearTimeout(longPressTimer);
    }


    return (
        <View className="xxm-stepper-ls">
            {+currentValue > min &&
                <React.Fragment>
                    <View
                        style={{
                            width: rest.buttonSize && `${rest.buttonSize}px`,
                            height: rest.buttonSize && `${rest.buttonSize}px`,
                        }}
                        className={
                            cls('xxm-stepper-ls__minus', {
                                'xxm-stepper-ls__minus--disabled': disabled || rest.disableMinus || +currentValue <= min
                            })
                        }
                        // hover-class="xxm-stepper-ls__minus--hover"
                        // hover-stay-time="70"
                        onClick={(e) => {
                            e.stopPropagation()
                            tapHandle('minus', e)
                        }}
                        onTouchStart={(e) => touchStartHandle('minus', e)}
                        onTouchEnd={() => touchEndHandle()}
                    >

                        <Icon name="minus-circle" size={24} color="#CECECE"></Icon>
                    </View>

                    <Input
                        type={integer ? 'number' : 'digit'}  //"{{ integer ? 'number' : 'digit' }}"
                        className={
                            cls('xxm-stepper-ls__input', {
                                'xxm-stepper-ls__input--disabled': disabled || rest.disableInput
                            })
                        }
                        value={`${currentValue || 0}`}
                        // disabled={disabled || rest.disableInput}
                        // onInput={onInput}
                        disabled

                    />
                </React.Fragment>
            }
            <View
                style={{
                    width: rest.buttonSize && `${rest.buttonSize}px`,
                    height: rest.buttonSize && `${rest.buttonSize}px`,
                }}
                className={
                    cls('xxm-stepper-ls__plus', {
                        'xxm-stepper-ls__plus--disabled': disabled || rest.disablePlus || +currentValue >= max
                    })
                }
                // hover-class="xxm-stepper-ls__minus--hover"
                // hover-stay-time="70"
                onClick={(e) => {
                    e.stopPropagation()
                    tapHandle('plus', e)
                } }
                onTouchStart={(e) => touchStartHandle('plus',e)}
                onTouchEnd={() => touchEndHandle()}
            >
                 <Icon name="jia" color="#F43443" size={22}></Icon> 
            </View>
        </View>
    )
}